import 'package:safety_platform/http.dart';
import 'package:safety_platform/models/task.dart';
import 'package:safety_platform/models/task_history_page.dart';
import 'package:safety_platform/models/task_page.dart';
import 'package:safety_platform/models/task_list_page.dart';
import 'package:safety_platform/models/task_item.dart';
import 'package:safety_platform/models/attachment.dart';
import 'package:safety_platform/pages/services.dart' as gs;
import 'dart:io';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart' show DioError;

final _taskCachePrefix = '__task_cache';
Future<Task> getTaskDetail(String id) async {
  String key = _createCacheKey(id);

  Task task = await getFormCache(key);

  if (task != null) {
    print('Get task from cache. $task');
    return task;
  }
  final String url = '/task/$id/';
  dynamic data = await httpGet(url);

  return Task.fromJson(data);
}
Future<TaskListPage> getTaskList({DateTime created}) async {
  String url = '/task/';
  Map<String,String> data = Map();
  if (created != null ){
     data['created'] = '${created.year}-${created.month}-${created.day}';
  }
  dynamic resp = await httpGet(url, data:data);
  return TaskListPage.fromJson(resp);
}
Future<TaskHistoryPage> getTaskHistoryList({DateTime startDate, DateTime endDate}) async {
  String url = '/task/history/';
  Map<String,String> data = Map();
  if (startDate != null) {
    data['start_date'] = '${startDate.year}-${startDate.month}-${startDate.day}';
  }
  if (endDate != null) {
    data['end_date'] = '${endDate.year}-${endDate.month}-${endDate.day}';
  }
  dynamic resp = await httpGet(url,data: data);

  return TaskHistoryPage.fromJson(resp);
}

Future<Null> deleteCache(String key) async {
  SharedPreferences sp = await SharedPreferences.getInstance();
  await sp.remove(key);
}

Future<Task> getFormCache(String key) async {
  SharedPreferences sp = await SharedPreferences.getInstance();
  String data = sp.getString(key);
  print('从缓存加载任务 【$key】，数据 【$data】');
  if (data != null) {
    return Task.fromJson(json.decode(data));
  }
  return null;
}

String _createCacheKey(String task) {
  
  return '$_taskCachePrefix-$task';
}

Future<Null> saveCache(Task task) async {
  Map<String, dynamic> data = task.toJson();
  SharedPreferences sp = await SharedPreferences.getInstance();
  await sp.setString(_createCacheKey(task.id), json.encode(data));
}

Future<Task> submitTask(Task task) async {
  final String url = '/task/${task.id}/';

  for (TaskItem item in task.items) {
    if (item.attachments != null && item.attachments.length > 0) {
      for (Attachment attachment in item.attachments) {
        if (attachment.uploadStatus == null) {
          continue;
        }
        if (attachment.uploadStatus != 'done') {
          if (attachment.uploadStatus == 'uploading') {
            // Cancel 上传请求
          }
          Attachment uploadedAttach = await gs.uploadPicture(
              File(attachment.localPath), attachment.screenName);
          attachment.id = uploadedAttach.id;
          attachment.url = uploadedAttach.url;
        }
      }
    }
  }
  Map<String, dynamic> data = task.toJson();
  print('提交任务: $data');
  try {
    dynamic resp = await httpPut(url, data: data);

    Task task = Task.fromJson(resp);

    await deleteCache(_createCacheKey(task.id));
    return task;
  } on DioError catch (e) {
    if (e.response != null) {
      print(e.response.data);
      if (e.response.statusCode == 400) {
        throw Exception('参数错误');
      } else if (e.response.statusCode == 500) {
        throw Exception('服务器错误');
      }
      throw Exception('未知错误');
      // print(e.response.headers) ;
      // print(e.response.request);
    } else {
      throw Exception('服务不可用');
      print(e.message);
    }
  }
}
